<?php

class Client_IndexController extends App_Controller_Action
{	
	public function indexAction()
	{
		$request=$this->getRequest();
		
		$success_msg = $request->getParam('success_msg');
		if (isset($success_msg)and(!empty($success_msg)))
			$this->view->success_msg=$success_msg;
			
		$error_msg = $request->getParam('error_msg');
		if (isset($error_msg)and(!empty($error_msg)))
			$this->view->error_msg=$error_msg;
			
    	$act = $request->getParam('act');   //get action 	
		
		$user_id = $this->getUserId();
		$user_role = 'client';
		
		$model_client = Model_UserFactory::create($user_role);
			
		if (isset($act)and($act=='remove')){
    		$dpt_id = $request->getParam('dpt_id');  	
    		$dpt_account_id = $request->getParam('dpt_account_id');  	
    		$client_id = $request->getParam('client_id');

			$dpt_login_arr=array();
			$dpt_login_arr['admin_user_id'] = '';
			$dpt_login_arr['url'] = $_SERVER['REQUEST_URI'];
			
    		$result=$model_client->removeClientService($user_id, $dpt_id, $dpt_account_id, $client_id, $dpt_login_arr);
			if ($result)
			{
				$this->view->success_msg="Service has been removed Successfully!";
				$this->_redirect("/client/index/index/success_msg/Service has been removed Successfully!");
			}else{
				$this->view->error_msg="Sorry, service removed failed.";
				$this->_redirect("/client/index/index/error_msg/Sorry, service removed failed.");
			}    		
		}else{
			if($request->isPost()){
				$data = $request->getParams();
				$notify_service_site = false;
				
				$dpt_id=$data['dpt_id'];
				$login_account = $data['account_id']; //spliting processed in login check
				$password=isset($data['password'])?$data['password']:"";
				
				$model_service = new Model_Service();
				$service_info = $model_service->getServiceInfo($dpt_id);
				$service_type = $service_info['service_type'];
				if ($service_type == 'like ppc' || $service_type == 'like yesupnet' )
				{
					$bootstrap = $this->getInvokeArg('bootstrap');
					$session = $bootstrap->getResource('session');
					$storage = new App_Auth_Storage_Session($session,'client');
					
					$login_account = $storage->getUserName();
					$password = "";
					$notify_service_site = true;
				}

				$dpt_check = $model_client->dptLoginCheck($dpt_id, $login_account, $password);
				//Zend_Debug::dump($dpt_check);//exit;
				if ($dpt_check['status']===true){
					$dpt_login_arr=array();
					$dpt_login_arr['dpt_account_login'] = $login_account;
					$dpt_login_arr['login_area'] = $dpt_check['login_area'];
					$dpt_login_arr['email'] = $dpt_check['email'];
					$dpt_login_arr['password'] = $password;
					$dpt_login_arr['admin_user_id'] = '';
					$dpt_login_arr['url'] = $_SERVER['REQUEST_URI'];
					$dpt_account_id = $dpt_check['dpt_account_id'];
					//Zend_Debug::dump($dpt_login_arr);exit;
					if ($notify_service_site){ //special for paypercall
	            		
						$model_site_service = Model_ServiceFactory::Create($dpt_id);
						$client_id = $dpt_check['dpt_account_id'];	
	            		$dpt_account_id = $model_site_service->addRemoteUser($client_id);	//$dpt_account_id:remote user_id		
					}
				
					if (($notify_service_site)and($dpt_account_id==0)){//add remote user failed
						$result=false;
					}else{					
						$result = $model_client->linkClientService($user_id, $dpt_id, $dpt_account_id, $dpt_login_arr);
					}
					
					if ($result)
					{
						$this->view->link_result="success";
						$this->view->link_dpt_id=$dpt_id;
						$this->view->link_login_account=$login_account;
						$this->view->link_dpt_account_id=$dpt_account_id;
						
						$this->view->success_msg="Service has been subscribed Successfully!";
					}else{
						$this->view->error_msg="Sorry, service subscribe failed.";
					}
				}else{
					$this->view->error_msg="Sorry, account validation failed: <b>".$dpt_check['message']."</b>";
				}
	
			}else{
				$ss = new Zend_Session_Namespace('service');
				if (isset($ss->link_result)){
					$this->view->link_result=$ss->link_result;
					$this->view->link_dpt_id=$ss->link_dpt_id;
					$this->view->link_login_account=$ss->link_login_account;
					$this->view->link_dpt_account_id=$ss->link_dpt_account_id;
					Zend_Session::namespaceUnset('service');
				}
			}
		}
		$model_userAdmin = new Model_UserAdmin();
		$news = $model_userAdmin->getLastNews($user_id);
		$this->view->news=$news;
		
		
		$model_service = new Model_Service();
		$all_services = $model_service->getAllService();
    	$all_groups = $model_service->getAllGroup();  			
		
		
		$client_services = $model_client->getClientService($user_id);
		
		$final_client_services = array();
		$pre_dpt_id=0;
		foreach ($client_services as $key => $item ){
			$dpt_id=$item['dpt_id'];
			if ($dpt_id==$pre_dpt_id){
				$final_client_services[ $pre_dpt_id ][]=$item;
			}else{
				$final_client_services[ $dpt_id ][]=$item;				
			}
			$pre_dpt_id = $dpt_id;
		}
		//Zend_Debug::dump($final_client_services);exit;
		
		$client_groups = $model_client->getClientGroup($user_id);
		//Zend_Debug::dump($client_groups);exit;
		
		$this->view->all_services=$all_services;
		$this->view->all_groups=$all_groups;		
		$this->view->client_services=$final_client_services;
		$this->view->client_groups=$client_groups;		
	}

	public function logoutAction()
	{
		//Zend_Session::namespaceUnset('ya');
		$session = $this->getSession();
		$session->unsetAll();

		$this->_redirect('/');
	}
	
	public function toServiceAction()
	{
		$this->_helper->layout->disableLayout();

		$dpt_id = $this->getRequest()->getParam('did');
		$dpt_account_id = $this->getRequest()->getParam('aid');
		$client_id = $this->getRequest()->getParam('cid');

		$model_service = new Model_Service();
		$login_url = $model_service->setSecurityKey($dpt_id, $dpt_account_id, $client_id);
		
		$valid_url = Zend_Uri::check($login_url);
		//Zend_Debug::dump($login_url);exit;
    
		error_log("to service set skey and redirect to - ".$login_url );
  
		if ($valid_url) $this->_redirect($login_url); 
		else throw new Exception('failed to remote site.');
	
		exit;
	}
	
	public function toDptServiceAction()
	{
		$this->_helper->layout->disableLayout();
		
		$dpt_id = $this->getRequest()->getParam('did');
		$dpt_account_id = $this->getRequest()->getParam('aid');
		$client_id = $this->getRequest()->getParam('cid');
		$url = $this->getRequest()->getParam('url'); 
		   	 
		$model_service = new Model_Service();
		$login_url = $model_service->setSecurityKey($dpt_id, $dpt_account_id, $client_id, $url);
		
		$valid_url = Zend_Uri::check($login_url);
		//Zend_Debug::dump($login_url);exit;
    
		error_log("to service set skey and redirect to - ".$valid_url );
  
		if ($valid_url) $this->_redirect($login_url); 
		else throw new Exception('failed to remote site.');
	
		exit;
	}
	
	
	public function toAccountAction()
	{		
	 	$user_id = $this->getUserId();
      	$model_service = new Model_ServiceCentral();
    	$link_accounts = $model_service->linkedAccounts($user_id);
      	
      	$client_id = $this->getRequest()->getParam('id');
		if(array_key_exists($client_id,$link_accounts[ $user_id ]))
		{
	      	$model_client = Model_UserFactory::create('client');
	      	$client = $model_client->getUser($client_id);
	      
	      	$session = $this->getSession();
	      	$storage = new App_Auth_Storage_Session($session,'client');
	      	//Zend_Debug::dump($storage->read());
	      	$storage->write(array(
	                    'user_id'=>$client_id,
	                    'user_name'=>$client['email'],
	                    'user_role'=>$client['role']));
	      	//Zend_Debug::dump($storage->read()); 
	
	    	$this->_redirect("/client");
		}else{
			echo "Auth failed";
			exit;
		}
		
	}
	
	
	/**
	 * Create service account action , use Yesup central account
     *
     * @param  none
     * @return none
	 */    
	
	public function createDptAccountAction()
	{
		$this->_helper->layout->disableLayout();
		$request = $this->getRequest();
		$dpt_id  = $request->getParam('dpt_id');
		$area  = $request->getParam('area');
		
		$user_id = $this->getUserId();
		$model_client = new Model_UserClient();
	 	$profile = $model_client->getProfile($user_id);
	 	
	 	if ( isset($area) and ($area=='advertiser' or $area=='publisher' or $area=='admin' ) )
	 		$profile['area'] = $area;
	 	
	 	if ( empty($profile['first_name']) or empty($profile['last_name']) or empty($profile['phone']) or empty($profile['company']) or empty($profile['address']) or empty($profile['city']) or empty($profile['state']) or empty($profile['country']) )
	 	{
	 		$this->_redirect("/client/profile/index/from/create/dpt_id/".$dpt_id."/area/".$area);
	 	}else{
	 		$model_dpt_service = Model_ServiceFactory::Create($dpt_id);
	 		$result = $model_dpt_service->createAccount($user_id, $dpt_id, $profile);
			if ($result)
			{
				$this->_redirect("/client/index/index/success_msg/Account has been created Successfully!");
			}else{
				$this->_redirect("/client/index/index/error_msg/Sorry, account creating failed. Reason could be duplicated email in system or database failed.");
			}
	 	}
		$this->_redirect("/client/");
	 	
		exit();
	}
	
	
}

